package com.liu.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2019/8/28 0028.
 */
@Component
public class NettyServer {



    private static  class SingletionNettyServer{

        static final NettyServer INSTANCE = new NettyServer();

    }

    public static NettyServer getInstance(){
        return  SingletionNettyServer.INSTANCE;
    }
    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap serverBootstrap;
    private ChannelFuture channelFuture;

    public NettyServer(){
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        serverBootstrap= new ServerBootstrap();
        serverBootstrap.group(mainGroup,subGroup).channel(NioServerSocketChannel.class)
                .childHandler(new NettyServerInitialzer());

        serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64,1024,65536));

    }

//   启动服务：
     public void start(){
        try {
            this.channelFuture= serverBootstrap.bind(81);
            this.channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();

        }finally {
            mainGroup.shutdownGracefully();
            subGroup.shutdownGracefully();
        }



         System.out.println("netty server run successfully !!!!");
     }




}
